# -*- coding: utf-8 -*-
"""
Author: chen xi
Date: 2025/5/14 上午11:34
File: gpio_control.py
"""
import RPi.GPIO as GPIO
import time
import argparse


def control_gpio(pin, state, duration):
    """
    控制指定GPIO引脚状态

    参数:
        pin: GPIO引脚号 (BCM编号)
        state: 输出状态 (HIGH/LOW)
        duration: 保持时间(秒)
    """
    try:
        # 设置GPIO模式为BCM
        GPIO.setmode(GPIO.BCM)
        
        # 设置GPIO引脚为输出模式
        GPIO.setup(pin, GPIO.OUT)
        
        # 设置GPIO引脚状态
        GPIO.output(pin, state)
        state_str = "HIGH" if state == GPIO.HIGH else "LOW"
        print(f"GPIO {pin} set to {state_str}")
        
        # 保持状态指定时间
        time.sleep(duration)
    
    finally:
        # 清理GPIO设置
        GPIO.cleanup()
        print(f"GPIO {pin} cleaned up")


if __name__ == "__main__":
    # 设置命令行参数解析
    parser = argparse.ArgumentParser(description='控制树莓派GPIO引脚')
    parser.add_argument('pin', type=int, help='GPIO引脚号(BCM编号)')
    parser.add_argument('--state', choices=['high', 'low'], default='low',
                        help='输出状态(high/low，默认为low)')
    parser.add_argument('--duration', type=float, default=5.0,
                        help='保持时间(秒，默认为5秒)')
    
    args = parser.parse_args()
    
    # 转换状态参数
    gpio_state = GPIO.HIGH if args.state == 'high' else GPIO.LOW
    
    # 调用控制函数
    control_gpio(args.pin, gpio_state, args.duration)